import Config, {configChange} from "../Config";
import {AxiosGet, AxiosPost} from "./HttpService";
import i18n from "../../i18n/i18n";
import {getItem, removeItem, setItem} from "./LocalDataService";
import {Watermark} from "@pansy/watermark";
import dayjs from "dayjs";
import JsEncrypt from "jsencrypt";
import {isDevelopment} from "../utils";

let localToken: string,
    localUserInfo: string = "userInfo",
    publicKey;

configChange((config: any) => {
    localToken = config.localToken;
});

// @ts-ignore
const getPublicKey: Function = async () => {
    const {data} = await AxiosGet("/sf-drs/platform/getPublicKey");
    publicKey = data;
    return publicKey
}

/**
 * 使用jsa加密
 * @param password 加密密码
 * @returns {PromiseLike<ArrayBuffer>}
 * @constructor
 */
// @ts-ignore
const JsEncryptPsw: Function = async (password) => {
    if (!publicKey) {
        publicKey = await getPublicKey();
    }
    const jse = new JsEncrypt();
    jse.setPublicKey(publicKey);
    return jse.encrypt(password);
}

// @ts-ignore
const login: Function = async (userInfo: object, isAutoHome: boolean = true): object => {
    const {data}: { data: any } = await AxiosPost("/sf-drs/platform/login", {
        ...userInfo
    });
    const token: string = data.accessToken;
    if (!token) {
        throw new Error(i18n.t("returnError"));
    }
    setItem(localToken, token);
    setItem(localUserInfo, data);
    isAutoHome && (window.location.href = "/");
    return data
};

const autoLogin: Function = async (urlParams, isAutoHome: boolean = true) => {
    const {data}: { data: any } = await AxiosGet("/sf-drs/platform/oauth/token" + urlParams);
    const token: string = data.accessToken;
    if (!token) {
        throw new Error(i18n.t("returnError"));
    }
    setItem(localToken, token);
    setItem(localUserInfo, data);
    isAutoHome && (window.location.href = "/");
    return data
}

// @ts-ignore
const logout: Function = async (): void => {
    removeItem(localToken);
    removeItem(localUserInfo);
    if (!isDevelopment()) {
        const {data} = await AxiosGet("/sf-drs/platform/oauth/url")
        const iframe = document.createElement('iframe');
        iframe.style.display = 'none';
        iframe.src = data.logoutUrl;
        document.body.appendChild(iframe);
        iframe.onload = function () {
            document.body.removeChild(iframe);
        };
        setTimeout(() => {
            if (iframe.parentNode) {
                document.body.removeChild(iframe);
            }
            window.location.reload();
        }, 3000);
    } else {
        window.location.reload();
    }
};

// @ts-ignore
const getUserInfo: Function = () => {
    return getItem(localUserInfo);
};

// @ts-ignore
const checkToken: Function = async () => {
    const {data}: { data: any } = await AxiosGet("/sf-drs/platform/check_token");
    let token: string = data.accessToken;
    if (!token) {
        throw new Error(i18n.t("returnError"));
    }
    setItem(localToken, token);
    setItem(localUserInfo, data);
    return data
};

// @ts-ignore
const setWatermark: Function = async () => {
    const {username} = getUserInfo()
    let baseFontSize = 16;
    let wh = 300
    let zoomLevel = window.devicePixelRatio || 1;
    const arr = [username, dayjs(new Date()).format(Config.dateFormat.time)];
    baseFontSize = baseFontSize / zoomLevel;
    wh = wh / zoomLevel;
    const water = new Watermark({
        text: arr,
        width: wh,
        height: wh,
        monitor: false,
        fontSize: baseFontSize,
    })
    window.addEventListener('resize', function () {
        let baseFontSize = 16;
        let wh = 300
        zoomLevel = window.devicePixelRatio || 1;
        baseFontSize = baseFontSize / zoomLevel;
        wh = wh / zoomLevel;
        water.update({
            text: arr,
            width: wh,
            height: wh,
            monitor: false,
            fontSize: baseFontSize,
        })
    })
}

export {
    getPublicKey,
    JsEncryptPsw,
    login,
    autoLogin,
    logout,
    getUserInfo,
    checkToken,
    setWatermark
};